package com.sfx.concurrent.demo.concurrent.AtomicTest.ABA;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-18
 * Time: 19:31
 */
@Slf4j(topic = "c.CASABAIssue")
public class CASABAIssue {
    private static AtomicReference<String> ref = new AtomicReference<>("A");
    public static void main(String[] args) throws InterruptedException {
        /**
         * 使用AtomicReference CAS操作并不能知道值已经被其他线程修改过了 例如 ABA问题
         * 要想解决就要引入版本号 AtomicStampedReference
         */
        //使用CAS将其A改变为C
        String prev = ref.get();
        other();
        Thread.sleep(1000);
        String next = "C";
        log.debug("A->C : {}",ref.compareAndSet(prev,next));
    }

    public static void other() throws InterruptedException {
        new Thread(()->{
           log.debug("A->B{}",ref.compareAndSet(ref.get(),"B"));
        },"t1").start();
        Thread.sleep(1000);
        new Thread(()->{
            log.debug("B->A{}",ref.compareAndSet(ref.get(),"A"));
        },"t2").start();
    }
}